import _ from 'lodash';
import Vue from 'vue';
import share from '@geekpark/share-action';
import { isWechat, isMobileView } from '@geekpark/ismobile';

import alertComponent from '../shared/alert';
import { config as shareConfig } from './share';

import Modal from 'bootstrap-modal';

// localstorage key
const KEY = 'rank';
const LOG = 'rank_log';
const TODAY = getToday();
const WECHAT = isWechat();

function init() {
  if(isMobileView()) {
    gon.awards = _.shuffle(gon.awards);
  }
  // init alert component
  let alertComp = alertComponent();
  let $modal = $('#vote-modal');

  // check if localstorage outdate then clear
  checkOutdate();

  let voteModal = new Vue({
    el: '#vote-modal',
    data: {
      awardsName: null,
      item: gon.awards[0].ranks[0],
      tipShare: false
    },
    methods: {
      open: function () {
        $modal.modal('show');
      },
      shareTo,
      toggleTip: function(type) {
        this.$set('tipShare', type);
      }
    }
  });
  let vote = new Vue({
    el: '#vote',
    data: {
      category: 0,
      awards: gon.awards.map(x => {
        return {
          info: x.info,
          ranks: x.ranks.map(rank => {
            return _.assign({}, rank, {
              isVoted: !notRanked(x.info.id, rank.rank.id),
              isShare: false,
              isWechat: false
            });
          })
        };
      })
    },
    methods: {
      vote: function (item, award) {
        const RANK_ID = item.rank.id;
        const awardID = award.info.id;

        item.$set('isVoted', true);
        if(!notRanked(awardID, RANK_ID)) {
          alertComp.open({
            message: '您今日已投过该产品了，去分享给更多人吧',
            type: 'warning'
          });
          return;
        }

        $.post(`/ranks/${RANK_ID}/vote`)
         .done(function (data) {
            if(WECHAT){
              changeTitle(`我在 Innoawards2015 为「${item.product.name}」投了一票，让最好的产品获得最高的荣誉，你也来为它点赞吧！`);
            }
            storeRank(awardID, RANK_ID);
            voteModal.open(item);
            voteModal.$set('item', item);
            voteModal.$set('awardsName', award.info.name);
         })
         .fail(function (jqXHR) {
            alertComp.open({
              message: JSON.parse(jqXHR.responseText).message,
              type: 'danger'
            });
         });
      },
      share: function (item) {
        item.$set('isWechat', false);
        item.$set('isShare', true);
      },
      shareTo,
      hideWechat: function (item) {
        item.$set('isWechat', false);
        item.$set('isShare', false);
      }
    }
  });

  $(window).scroll(function () {
    vote.$data.awards.forEach(x => {
      x.ranks.forEach(y => {
        y.isShare = false;
      });
    });
  });
}


// check has ranked
function notRanked(awardID, rankID) {
  let data = getLocalStorage();
  if(typeof data[awardID] !== 'undefined') {
    return data[awardID].indexOf(rankID) === -1;
  } else {
    return true;
  }
}

// store rank to localstorage
function storeRank(awardID, rankID) {
  let data = getLocalStorage();
  if(!Array.isArray(data[awardID])) data[awardID] = [];
  data[awardID].push(rankID);
  localStorage.setItem(KEY, JSON.stringify(data));
  localStorage.setItem(LOG, JSON.stringify(TODAY));
}


function shareTo(type, item) {
  let pic = item.product.logo.url;
  if(!/http/.test(pic)) {
    pic = location.origin + pic;
  }
  share.run({
    type,
    text: `我在 Innoawards2015 为「${item.product.name}」投了一票，让最好的产品获得最高的荣誉，你也来为它点赞吧！`,
    thumb:  pic
  });
}

// check if log outdate then clean log
function needClearDayLock() {
  let dateLog = localStorage.getItem(LOG);

  if(dateLog && JSON.parse(dateLog)) {
    let log = JSON.parse(dateLog);
    return !_.isEqual(log, TODAY);
  } else {
    return true;
  }
}

function checkOutdate() {
  if(needClearDayLock()) {
    console.info('clear outdate vote lock !');
    localStorage.removeItem(LOG);
    localStorage.removeItem(KEY);
  }
}

// util function for read data from localstorage
function getLocalStorage() {
  let rank = localStorage.getItem(KEY);
  let parse = rank ? JSON.parse(rank) : false;
  return parse || {};
}

function getToday() {
  let logDate = new Date();
  return {
    month: logDate.getMonth(),
    day: logDate.getDate()
  };
}

function changeTitle(str) {
  window.title = str;
  $('title').text(str);
}

export default { init };
